<?php
/** 群组
 * Created by PhpStorm.
 * User: denh
 * Date: 16/5/30
 * Time: 下午1:36
 */
class GroupController extends BaseController {

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);
        $this->redirectToWeixinForOpenid();
        $do_user = new Do用户();
        $do_user->set_openID($this->openId());
        $do_user->where($do_user->data)->row();
        $this->do_user = $do_user;
    }

    public function webSocket_video(){
        date_default_timezone_set('Asia/Shanghai');
        $openId = $this->openId();
        $group_id = $this->request('groupId', '', true);
        $user_id = $this->do_user->get_id();
        $video_url = $this->request('video_url', '', true);
        if(empty($openId) or empty($video_url) or empty($group_id)) {
            exit('参数错误');
        }

        $bm = new CUI数据中心(Page::b病历管理,$openId);
        $群聊天 = new C群聊天('');
        $c用户 = new C用户($bm->vo信息中心);
        //$群信息 = $c用户->fc查找群信息($group_id);
        $detail_group = $this->group_detail($group_id);
        $用户是否是群用户 = $c用户->fc查看用户是否是群用户($group_id);
        if(!$用户是否是群用户){
            $加入视频群聊 = $c用户->fj加入视频群聊($group_id);
        }
        $群聊天->f进入课程($user_id, $group_id);
        $myself = $this->do_user;
        $time = date("Y-m-d H:i:s",time());
        require $this->template;
    }

    //判断用户是否是群成员
    public function judge_user_group(){
        $groupId = $this->request('群id', '', true);
        $userId = $this->do_user->get_id();
        $doGroupMember = new Do群成员();
        $doGroupMember->set_群id($groupId);
        $doGroupMember->set_用户id($userId);
        $groupMember = $doGroupMember->where($doGroupMember->data)->count();

        echo $groupMember;
    }

    /*群聊天*/
    public function chat() {
        date_default_timezone_set('Asia/Shanghai');
        $do_meet = new Do会议表();
        $do_group = new Do群详情();
        $group_id = $this->request('groupId');
        $user_id = $this->do_user->get_id();
        // $用户是否是群用户 = $c用户->fc查看用户是否是群用户($group_id);
        $is_group_user = $this->check_group_user($group_id,$user_id);

        $group_detail = $this->group_detail($group_id);
        //用户可创建的一般群，父id 为0
        $group_list_0= $this->url('group','groupList');
        //$群聊列表 = $bm->生成有效链接('Seller21QunLiao_List',$_GET['state']);
        //新生儿六次会议链接 ,父id 为1
        $group_xinshenger = $this->url('conference','xinshenger_qunzu');
        if($group_detail->data['父id'] == 1){
            $群列表 = $group_xinshenger;
        }else if($group_detail->data['父id'] == 0){
            $群列表 = $group_list_0;
        }

        $huiyi_res= $do_meet->fields('a.id id,下一步')->leftJoin($do_group,'b','a.id=b.父id')->where('b.id='.$group_id)->row();
        $meet_id = isset($_GET['meet_id'])?$_GET['meet_id']:$huiyi_res->data['id'];

        $sql = "select * from 会议表 where id= ".$meet_id;
        $huiyi_qun_res = pdo()->selectOne($sql);
        $paramArray= array(
            'groupId'=>$group_id,
            'meet_id'=>$meet_id
        );

        if(empty($is_group_user['id'])){
            if($huiyi_qun_res){
                $group_error_url = $this->url('group','group_error');
                echo "<script>location.href='".$group_error_url."'</script>";
            }else{
                echo "<script>alert('您不是群成员或未通过审核');location.replace(location.href='".$群列表."');</script>";
            }
        }

        $back = Tools::url('conference',$huiyi_res->data['下一步'],$paramArray);
        if($_GET['tuisong']=='yes'){
            echo "<script>location.href='".$back."'</script>";
        }
        $group_doc_url = $this->url('group','groupDoc',$paramArray);
        //群成员
        $group_user_url = $this->url('group','groupUsers',$paramArray);
        //群主题
        $group_card_url = $this->url('group','groupCard',$paramArray);
        //用户信息
        $myself = $this->do_user;
        $time = date("Y-m-d H:i:s",time());
        require $this->template;
    }

    /*群成员列表*/
    public function groupUsers() {
        $do_group = new Do群详情();
        $do_user = new Do用户();
        $do_groupUser = new Do群成员();
        $do_doctor = new Do医师详情();

        $user_id= $this->do_user->get_id();
        $paramArray = array('meet_id'=>$_GET['meet_id'],'groupId'=>$_GET['groupId']);
        $websoke_qun_url  = $this->url('group','chat',$paramArray);
        $group_detail = $this->group_detail($_GET['groupId']);
        $state_pass = "!='未审核'";
        $state_no = "='未审核'";
        $do_groupUser
            ->leftJoin($do_user,'b','a.`用户id` =b.id')
            ->leftJoin($do_doctor,'c','b.id = c.`用户id`');
        $no_group_user =  $do_groupUser->fields('a.*,b.name,b.认证,b.头像,c.医院,c.职务')->where(" a.`群id`='".$_GET['groupId']."' and a.`角色`".$state_no."")->rows();

        $group_user = $do_groupUser->fields('a.*,b.name,b.认证,b.头像,c.医院,c.职务')->where(" a.`群id`='".$_GET['groupId']."' and a.`角色`".$state_pass."")->rows();
        $myself = $this->do_user;
        $is_group_user = $this->check_group_user($_GET['groupId'],$user_id);
        $group_user_id = $is_group_user['id'];
        require $this->template;

    }


    /*群名片*/
    public function groupCard() {
        $群id = $_GET['groupId'];
        $用户id = $this->do_user->get_id();
        $openId = $this->do_user->get_openID();
        $group_detail = $this->group_detail($群id);
        //$是否是群用户= $c用户->fc查看用户是否是群用户($群id);
         $is_group_user = $this->check_group_user($群id,$用户id);
        $paramArray = array('meet_id'=>$_GET['meet_id'],'groupId'=>$群id);
        $websoke_qun_url  = $this->url('group','chat',$paramArray);
        //编辑群主题
        $update_group_url =$this->url('group','groupUpdate',$paramArray);
        require $this->template;
    }

    /*创建群组*/
    public function groupCreate() {
        if($_POST)
        {
            $openId=$this->openId();
            $bm=new CUI数据中心('Seller20CreateGroup',$openId);
            $chat_url = $this->url('group','chat');
            $c用户 = new C用户($bm->vo信息中心);
            $group_id = $c用户->fc创建群组();
            if($group_id)
            {
                echo "<script>alert('群组创建成功！');location.replace(location.href='".$chat_url."&groupId=".$group_id."');</script>";
            }
        }
        require $this->template;
    }

    /*群组列表*/
    public function groupList() {
        $do_user = new Do用户();
        $user_id = $this->do_user->get_id();
        $chat_url = $this->url('group','chat');
        $creat_group_url = $this->url('group','groupCreate');
        if($_GET['父id']) $父id=$_GET['父id'];else  $父id='';
        require $this->template;
    }


    //统计在线时长
    function out_group_lx() {
        $groupId = $this->request('groupId','', true);
        $用户id = $this->do_user->get_id();

        $sql = "update `群离线`
                set `最后在线时间` = ?, `time_length` = `time_length` + 10
                where `用户id` = ? and `群id` = ?";
        $re = pdo()->prepare_execute($sql, array(date("Y-m-d H:i:s"), $用户id, $groupId));

        if (!$re) {
            logger()->logInfo("out_group_lx: 更新失败, ".$groupId.", ".$用户id);
        }
        $this->jsonOutPut(0, 'ok');
    }



    //编辑群主题，修改群名称及简介 权限：群主
    function groupUpdate(){
        $group_id=$_GET['groupId'];
        $group_detail = $this->group_detail($group_id);
        $parm = array(
            'groupId'=>$group_id,
            'meet_id'=>$_GET['meet_id']
        );
        $group_card_url = $this->url('group','groupCard',$parm);
        if($_POST)
        {
            $do_group = new Do群详情();
            $do_group->set_id($group_id);
            $do_group->set_群名称($_POST['群名称']);
            $do_group->set_主题($_POST['content']);
            $res = $do_group->save();
            if($res)
            {
                echo "<script>alert('修改成功！');location.replace(location.href='".$group_card_url."');</script>";
            }
        }

        require $this->template;
    }

    //群文档--仅对第六次新生儿会议 中的循环专业委员会
    function groupDoc(){
        $parm = array(
            'groupId'=>$_GET['groupId']
        );
      $chat_url = $this->url('group','chat',$parm);
        require $this->template;
    }
    //查看群信息
    function group_detail($group_id){
        $do_group = new Do群详情();
        $group_detail = $do_group->where('id = '.$group_id)->row();
        return $group_detail;
    }

    //查看用户是否是群用户
    function  check_group_user($group_id,$user_id){
        $sql = "SELECT a.*,(SELECT b.`最后在线时间` FROM `群离线` b WHERE a.`用户id`=b.`用户id` AND a.`群id`=b.`群id`) AS `离线时间` FROM `群成员` a  WHERE a.`群id` =".$group_id." and a.`用户id`=".$user_id." and a.`角色` !='未审核'";
        $is_group_user = pdo()->selectOne($sql);
        return $is_group_user;
    }

    //不是群成员，提示页
    function group_error(){
        require $this->template;
    }

    function downLoadWxFile() {
        logger()->logInfo("===call downLoadWxFile===");###
        $serverId = $this->request('serverId', '', true);
        $type = $this->request('type','audio');

        require_once ROOT_PATH . 'tools/getid3/getid3.php';

        $Tools = new Tools();
        $Token = $Tools->fh通过公众号id获取公众号Token信息(G_SERV_ID);
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$Token."&media_id=".$serverId;

        if ($type == 'image') {
            $文件地址 = '/home/wwwroot/Ram_disk/img';

            $图片 = $serverId.".jpg";

            if(!is_dir($文件地址)){
                mkdir($文件地址);
            }

            $ret2 = $Tools->curl_get_page_新($url);
            $c生成文件 = $Tools->f生成文件($文件地址.'/'.$图片, $ret2);
            if ($c生成文件) {
                $fileUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Ram_disk/img/'. $图片;
                $imageInfo = getimagesize($文件地址.'/'.$图片);
                $file = array(
                    'name' => '',
                    'size' => filesize($文件地址.'/'.$图片),
                    'md5' => md5(file_get_contents($文件地址.'/'.$图片)),
                    'url' => $fileUrl,
                    'ext' => 'jpg',
                    'w' => $imageInfo[0],
                    'h' => $imageInfo[1],
                );
                logger()->logInfo("file:".var_export($file, true));###
                $this->jsonOutPut(0, '', $file);
            }


        } else {
            $文件地址 = '/home/wwwroot/Ram_disk';

            if(!is_dir($文件地址)) {
                exec(" mkdir ".$文件地址);
                exec("mount -t ramfs none ".$文件地址);
            }

            $ret = $Tools->curl_get_page_新($url);
            $file = $文件地址.'/'.$serverId.'.amr';
            $c生成文件 = $Tools->f生成文件($file, $ret);

            $filePath = $文件地址 . '/'. $serverId. '.mp3';

            if($c生成文件) {
                exec("chmod -R 777 ".$file);
                exec("ffmpeg -i  ". $file ." ".$filePath);
                exec("chmod -R 777 ".$filePath);
                if(is_file($文件地址."/".$serverId.".mp3")) {
                    exec('rm -f '.$file);

                    $fileUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Ram_disk/'. $serverId. '.mp3';

                    $getID3 = new getID3();
                    $ThisFileInfo = $getID3->analyze($filePath);
                    $file = array(
                        'name' => '',
                        'size' => $ThisFileInfo['filesize'],
                        'md5' => md5(file_get_contents($filePath)),
                        'url' => $fileUrl,
                        'ext' => 'mp3',
                        'dur' => $ThisFileInfo['playtime_seconds'] * 1000,
                    );
                    logger()->logInfo("file:".var_export($file, true));###
                    $this->jsonOutPut(0, '', $file);
                }
            }
        }
    }
}